﻿using AutoMapper;
using MediatR;
using Microsoft.Extensions.Logging;
using RBAC.Domain.SalesManage;
using RBAC.Domain.Dto.Output;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Read.Api.Application.Command.ERP.SalesManagement;
using System.Linq;

namespace RBAC.Read.Api.Application.Handler.ERP.SalesManagement
{
    /// <summary>
    /// 销售订单分页查询处理器
    /// </summary>
    public class SalesOrderPageHandler : IRequestHandler<SalesOrderPageCommand, APIPaging<SalesOrderDto>>
    {
        private readonly IBaseRepository<SalesOrder> salesOrderRepository;
        private readonly ILogger<SalesOrderPageHandler> logger;
        private readonly IMapper mapper;

        public SalesOrderPageHandler(IBaseRepository<SalesOrder> salesOrderRepository,
            ILogger<SalesOrderPageHandler> logger,
            IMapper mapper)
        {
            this.salesOrderRepository = salesOrderRepository;
            this.logger = logger;
            this.mapper = mapper;
        }

        /// <summary>
        /// 处理销售订单分页查询
        /// </summary>
        /// <param name="request">查询请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>分页结果</returns>
        public Task<APIPaging<SalesOrderDto>> Handle(SalesOrderPageCommand request, CancellationToken cancellationToken)
        {
            APIPaging<SalesOrderDto> result = new APIPaging<SalesOrderDto>();

            try
            {
                logger.LogInformation("开始查询销售订单分页数据，页码：{PageIndex}，每页数量：{PageSize}",
                    request.PageIndex, request.PageSize);

                // 构建查询条件
                var whereClause = BuildWhereClause(request);
                var parameters = BuildParameters(request);

                // 执行分页查询
                var (data, totalCount) = salesOrderRepository.GetPaged(
                    request.PageIndex,
                    request.PageSize,
                    whereClause,
                    request.OrderBy,
                    parameters);

                // 映射到DTO
                var dtoData = mapper.Map<List<SalesOrderDto>>(data);

                // 设置返回结果
                result.Code = APIEnums.Success;
                result.PageDatas = dtoData;
                result.TotalCount = totalCount;
                result.Msg = "获取销售订单列表成功";

                logger.LogInformation("销售订单分页查询成功，总记录数：{TotalCount}，当前页记录数：{CurrentPageCount}",
                    totalCount, dtoData.Count);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "销售订单分页查询失败：{Message}", ex.Message);
                result.Code = APIEnums.Error;
                result.Msg = "获取销售订单列表失败";
                result.PageDatas = new List<SalesOrderDto>();
                result.TotalCount = 0;
            }

            return Task.FromResult(result);
        }

        /// <summary>
        /// 构建WHERE查询条件
        /// </summary>
        /// <param name="request">查询请求</param>
        /// <returns>WHERE条件字符串</returns>
        private string BuildWhereClause(SalesOrderPageCommand request)
        {
            var conditions = new List<string>();

            if (!string.IsNullOrEmpty(request.OrderCode))
            {
                conditions.Add("OrderCode LIKE @OrderCode");
            }

            if (!string.IsNullOrEmpty(request.CustomerName))
            {
                conditions.Add("CustomerName LIKE @CustomerName");
            }

            if (!string.IsNullOrEmpty(request.OrderStatus))
            {
                conditions.Add("OrderStatus = @OrderStatus");
            }

            if (!string.IsNullOrEmpty(request.BusinessStatus))
            {
                conditions.Add("BusinessStatus = @BusinessStatus");
            }

            if (request.StartDate.HasValue)
            {
                conditions.Add("OrderDate >= @StartDate");
            }

            if (request.EndDate.HasValue)
            {
                conditions.Add("OrderDate <= @EndDate");
            }

            if (!string.IsNullOrEmpty(request.SalesPerson))
            {
                conditions.Add("SalesPerson LIKE @SalesPerson");
            }

            return conditions.Count > 0 ? string.Join(" AND ", conditions) : "";
        }

        /// <summary>
        /// 构建查询参数
        /// </summary>
        /// <param name="request">查询请求</param>
        /// <returns>查询参数字典</returns>
        private object BuildParameters(SalesOrderPageCommand request)
        {
            var parameters = new Dictionary<string, object>();

            if (!string.IsNullOrEmpty(request.OrderCode))
            {
                parameters["OrderCode"] = $"%{request.OrderCode}%";
            }

            if (!string.IsNullOrEmpty(request.CustomerName))
            {
                parameters["CustomerName"] = $"%{request.CustomerName}%";
            }

            if (!string.IsNullOrEmpty(request.OrderStatus))
            {
                parameters["OrderStatus"] = request.OrderStatus;
            }

            if (!string.IsNullOrEmpty(request.BusinessStatus))
            {
                parameters["BusinessStatus"] = request.BusinessStatus;
            }

            if (request.StartDate.HasValue)
            {
                parameters["StartDate"] = request.StartDate.Value.Date;
            }

            if (request.EndDate.HasValue)
            {
                parameters["EndDate"] = request.EndDate.Value.Date.AddDays(1).AddSeconds(-1); // 包含结束日期当天
            }

            if (!string.IsNullOrEmpty(request.SalesPerson))
            {
                parameters["SalesPerson"] = $"%{request.SalesPerson}%";
            }

            return parameters;
        }
    }
}
